From 6aa5fa70cf5ccd2825e5657ec1a90e370dea3bcf Mon Sep 17 00:00:00 2001
From: Rafi Zadanly <zadanlyr@gmail.com>
Date: Mon, 16 Oct 2023 11:16:33 +0700
Subject: Fix buy action before and after login

---
 src/pages/shop/product/[slug].jsx | 28 ++++++++++++++++++++++++++--
 1 file changed, 26 insertions(+), 2 deletions(-)

(limited to 'src/pages/shop/product/[slug].jsx')

diff --git a/src/pages/shop/product/[slug].jsx b/src/pages/shop/product/[slug].jsx
index 4c17ab37..d8366d3c 100644
--- a/src/pages/shop/product/[slug].jsx
+++ b/src/pages/shop/product/[slug].jsx
@@ -9,6 +9,7 @@ import cookie from 'cookie'
 import axios from 'axios'
 import { useProductContext } from '@/contexts/ProductContext'
 import { useEffect } from 'react'
+import { updateItemCart } from '@/core/utils/cart'
 
 const BasicLayout = dynamic(() => import('@/core/components/layouts/BasicLayout'))
 const Product = dynamic(() => import('@/lib/product/components/Product/Product'))
@@ -22,7 +23,10 @@ export async function getServerSideProps(context) {
   const authToken = auth?.token || ''
 
   let response = await axios(
-    `${process.env.NEXT_PUBLIC_SELF_HOST}/api/shop/product-detail?id=` + getIdFromSlug(slug) +'&auth=' + tier
+    `${process.env.NEXT_PUBLIC_SELF_HOST}/api/shop/product-detail?id=` +
+      getIdFromSlug(slug) +
+      '&auth=' +
+      tier
   )
   let product = response.data
   // let productSolr = await productApi({ id: getIdFromSlug(slug), headers: { Token: authToken } })
@@ -39,7 +43,6 @@ export async function getServerSideProps(context) {
 }
 
 export default function ProductDetail({ product }) {
-  console.log(product);
   const router = useRouter()
   const { setProduct } = useProductContext()
 
@@ -49,6 +52,27 @@ export default function ProductDetail({ product }) {
     }
   }, [product, setProduct])
 
+  useEffect(() => {
+    const { action, variantId, qty } = router.query
+    const addToCart = async () => {
+      const data = {
+        productId: variantId,
+        quantity: qty,
+        selected: true,
+        programLineId: null,
+        source: action
+      }
+      console.log('data dr test', data)
+      await updateItemCart(data)
+      const redirectURL = action === 'buy' ? '/shop/checkout?source=buy' : '/shop/cart'
+      router.push(redirectURL)
+    }
+
+    if (action && variantId && qty) {
+      addToCart()
+    }
+  }, [router])
+
   if (!product) return <PageNotFound />
 
   return (
-- 
cgit v1.2.3

